
//这个类是用于初始化一个websocket连接的函数
export class GuestKeepAlive {
    constructor(token){
        if (token == "") {
            console.error("Start session err: token is null")
        }
        //从浏览器获取的token
        this.token = token;
        this.url = "/msg/GuestKeepAlive";
        this.socket = null;
        this.createConn()
        // 添加unload事件的处理函数
        window.addEventListener('unload', this.close.bind(this));
    }
    createConn(){
        try{
            this.socket = new window.WebSocket(this.url);
        }catch(e){
            console.warn("Guest webSocket connection failed in web environment, start to reconnect")
                try {
                    this.socket = new window.WebSocket(`${document.location.protocol === 'https:' ? 'wss://' : 'ws://'}${document.location.host}${this.url}`);
                } catch (e) {
                    console.error("Guest webSocket connection failed in web environment: ", e);
                    throw e;
                }
        }
        this.socket.onopen = this.onOpen.bind(this);
        this.socket.onmessage = this.onMessage.bind(this);
        this.socket.onclose = this.onClose.bind(this);
        this.socket.onerror = this.onError.bind(this);

    }
    async onOpen(event) {
        console.log("WebSocket is connected: ", event.target);

        // 检查token是否为空
        if (!this.token) {
            console.error("formatToken failed");
            throw new Error("formatToken failed");
        }

        // 发送token
        console.log("发送数据：",this.token)
        this.socket.send(this.token);
    }

    async onMessage(event) {
        // 检查是否收到客户端主动关闭指令
        console.log("接收到了信息",event.data)
        if (event.data === "client actively close") {
            console.log("Received close for login from server");
            this.close();
        }

        // 检查是否收到关闭指令
        if (event.data === "close") {
            console.log("Received close from server");
            this.socket.close();
        }
        // 检查是否收到心跳包
        if (event.data === "heartbeat") {
            console.log("Received heartbeat from server");
            // 检查token是否为空
            if (!this.token) {
                console.error("formatToken failed");
                throw new Error("formatToken failed");
            }

            console.log("发送数据：",this.token)
            this.socket.send(this.token);
        }
    }

    onClose(event) {
        if (event.wasClean) {
            console.log("WebSocket is closed now: ", event.code, event.reason);
        } else {
            console.warn("WebSocket is closed now: ", event.code, event.reason);
            // 如果连接被异常关闭，尝试重新连接
            if (event.code === 1006) {
                console.log("Trying to reconnect...");
                this.createConn();
            }
        }
    }

    onError(event) {
        console.error("WebSocket error observed:", event);
        throw new Error("WebSocket error observed:" + event);
    }

    // 关闭WebSocket连接
    close() {
        // 检查是否存在WebSocket连接
        if (!this.socket) {
            console.error("WebSocket is not connected");
            throw new Error("WebSocket is not connected");
        }
        // 若WebSocket已经关闭，则直接返回
        if (this.socket.readyState === WebSocket.CLOSED) {
            console.warn("WebSocket is already closed");
            return;
        }

        // 向服务端发送用户关闭事件
        this.socket.send("close");

        this.socket.close();
    }

    testclose(){
         // 检查是否存在WebSocket连接
         if (!this.socket) {
            console.error("WebSocket is not connected");
            throw new Error("WebSocket is not connected");
        }
        // // 若WebSocket已经关闭，则直接返回
        if (this.socket.readyState === WebSocket.CLOSED) {
            console.warn("WebSocket is already closed");
            return;
        }
        this.socket.close();
        console.log("关闭了websocket连接")
    }
}


export class RegKeepAlive {
    constructor(token) {
        // 检查userId是否为空
        if (!token) {
            console.error("userId is null");
            throw new Error("userId is null");
        }

        this.url =  "/msg/RegKeepAlive";
        this.socket = null;
        this.token = token;
        this.userAgent = navigator.userAgent;

        // 连接到WebSocket服务器
        try {
            this.connect()
        } catch (e) {
            console.error(e)
            return
        }

        // 添加unload事件的处理函数
        window.addEventListener('unload', this.close.bind(this));
    }

    connect() {
        // 若已存在WebSocket连接，则先关闭
        if (this.socket) {
            this.socket.close();
        }

        console.log("WebSocket is connecting...")
            // Web 环境
            try {
                this.socket = new window.WebSocket(this.url);
            } catch (e) {
                console.warn("Guest webSocket connection failed in web environment, start to reconnect")
                try {
                    this.socket = new window.WebSocket(`${document.location.protocol === 'https:' ? 'wss://' : 'ws://'}${document.location.host}${this.url}`);
                } catch (e) {
                    console.error("Guest webSocket connection failed in web environment: ", e);
                    throw e;
                }
            }
        

        this.socket.onopen = this.onOpen.bind(this);
        this.socket.onmessage = this.onMessage.bind(this);
        this.socket.onclose = this.onClose.bind(this);
        this.socket.onerror = this.onError.bind(this);
    }

    async onOpen(event) {
        console.log("WebSocket is connected: ", event.target);

        // 检查token是否为空
        if (!this.token) {
            console.error("formatToken failed");
            throw new Error("formatToken failed");
        }

        // 发送token
        this.socket.send(this.token);
    }

    async onMessage(event) {
        // 检查是否收到客户端主动关闭指令
        if (event.data === "client actively close") {
            console.log("Received close for login from server");
            this.close();
        }

        // 检查是否收到关闭指令
        if (event.data === "close") {
            console.log("Received close from server");
            this.socket.close();
        }

        // 检查是否收到心跳包
        if (event.data === "heartbeat") {
            console.log("Received heartbeat from server");

            // 检查token是否为空
            if (!this.token) {
                console.error("formatToken failed");
                throw new Error("formatToken failed");
            }

            this.socket.send(this.token);
        }

    }

    onClose(event) {
        if (event.wasClean) {
            console.log("WebSocket is closed now: ", event.code, event.reason);
        } else {
            console.warn("WebSocket is closed now: ", event.code, event.reason);
            // 如果连接被异常关闭，尝试重新连接
            if (event.code === 1006) {
                console.log("Trying to reconnect...");
                this.connect();
            }
        }
    }

    onError(event) {
        console.error("WebSocket error observed:", event);
        throw new Error("WebSocket error observed:" + event);
    }

    // 关闭WebSocket连接
    close() {
        // 检查是否存在WebSocket连接
        if (!this.socket) {
            console.error("WebSocket is not connected");
            throw new Error("WebSocket is not connected");
        }
        // 若WebSocket已经关闭，则直接返回
        if (this.socket.readyState === WebSocket.CLOSED) {
            console.warn("WebSocket is already closed");
            return;
        }

        // 向服务端发送用户关闭事件
        this.socket.send("close");

        this.socket.close();
    }
    testclose(){
        // 检查是否存在WebSocket连接
        if (!this.socket) {
           console.error("WebSocket is not connected");
           throw new Error("WebSocket is not connected");
       }
       // // 若WebSocket已经关闭，则直接返回
       if (this.socket.readyState === WebSocket.CLOSED) {
           console.warn("WebSocket is already closed");
           return;
       }
       this.socket.close();
       console.log("关闭了websocket连接")
   }
}